<template>
  <div class="tinymce-editor">
    <editor
      v-if="!reloading"
      v-model="myValue"
      :init="init"
      :disabled="disabled"
      @onClick="onClick">

    </editor>
  </div>
</template>
<!--配置详见：https://blog.csdn.net/zjiang1994/article/details/79856058-->
<!--插件开发详见知乎《三种插件开发模式，带你玩废tinymce》-->
<script>
  import tinymce from 'tinymce/tinymce'
  import Editor from '@tinymce/tinymce-vue'
  import 'tinymce/themes/silver/theme'
  import 'tinymce/plugins/image'
  import 'tinymce/plugins/link'
  import 'tinymce/plugins/media'
  import 'tinymce/plugins/table'
  import 'tinymce/plugins/lists'
  import 'tinymce/plugins/contextmenu'
  import 'tinymce/plugins/wordcount'
  import 'tinymce/plugins/colorpicker'
  import 'tinymce/plugins/textcolor'
  import 'tinymce/plugins/fullscreen'
  import 'tinymce/icons/default'
  import "tinymce/plugins/code";
  import "tinymce/plugins/preview";
  import "tinymce/plugins/charmap";
  import "tinymce/plugins/imagetools";
  // import "tinymce/plugins/emoticons";
  import "tinymce/plugins/hr";
  import "tinymce/plugins/pagebreak";
  import "tinymce/plugins/insertdatetime";
  import "tinymce/plugins/autolink";
  import { uploadAction,getFileAccessHttpUrl } from '@/api/manage'
  // import { getVmParentByName } from '@/utils/util'
  import "./tinymcePlugins/saveBtn.js";


  export default {
    components: {
      Editor
    },
    props: {
      value: {
        type: String,
        required:false
      },
      triggerChange:{
        type: Boolean,
        default: false,
        required:false
      },
      disabled: {
        type: Boolean,
        default: false
      },
      plugins: {
        type: [String, Array],
        default: 'lists image link media table textcolor wordcount contextmenu fullscreen code preview charmap imagetools icons hr pagebreak insertdatetime autolink saveBtn'//emoticons
      },
      toolbar: {
        type: [String, Array],
        // default: 'undo redo |  formatselect | bold italic | forecolor | backcolor | underline | hr | pagebreak | strikethrough | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | lists link unlink image media table charmap insertdatetime | removeformat | fullscreen | code | preview',//emoticons
        default: 'undo redo formatselect bold italic forecolor backcolor underline hr pagebreak strikethrough alignleft aligncenter alignright alignjustify bullist numlist outdent indent lists link unlink image media table charmap insertdatetime removeformat code preview selectall saveBtn',//emoticons
        // default: 'undo redo formatselect bold italic forecolor backcolor underline hr pagebreak strikethrough alignleft aligncenter alignright alignjustify bullist numlist outdent indent lists link unlink table charmap insertdatetime removeformat code preview selectall saveBtn',//【图片视频上传】等小程审核通过再打开 image media
        branding:false
      }
    },
    data() {
      return {
        //初始化配置
        init: {
          language_url: '/tinymce/langs/zh_CN.js',
          language: 'zh_CN',
          skin_url: '/tinymce/skins/lightgray',
          // height: 667+218,//218是多出给工具栏的
          height: window.innerHeight-16,//-16配合样式处理，将底部字数状态栏提上，以保持美观
          // height:800,
          // width: 375,
          // width: '',
          plugins: this.plugins,
          toolbar: this.toolbar,
          branding: false,
          menubar: false,
          //启用菜单栏并显示如下项 [文件 编辑 插入 格式 表格]
          // menubar: 'file edit insert view format table',
          // 配置每个菜单栏的子菜单项（如下是默认配置）
          // menu: {
          //   file: {title: 'File', items: 'newdocument'},
          //   edit: {title: 'Edit', items: 'undo redo | cut copy paste pastetext | selectall'},
          //   insert: {title: 'Insert', items: 'link media | template hr'},
          //   view: {title: 'View', items: 'visualaid'},
          //   format: {title: 'Format', items: 'bold italic underline strikethrough superscript subscript | formats | removeformat'},
          //   table: {title: 'Table', items: 'inserttable tableprops deletetable | cell row column'},
          // },
          toolbar_drawer: false,
          // toolbar_drawer: true,
          //emoticons_database_url:'/tinymce/emoticons/js/emojis.js',
          /* emoticons_append:{
            "diy1": {
              "keywords": ["diy1"],
              "char": "\uD83E\uDD2F",
              "category": "animals_and_nature"
            }
          }, */

          images_upload_handler: (blobInfo, success) => {
            let formData = new FormData()
            formData.append('file', blobInfo.blob(), blobInfo.filename());
            formData.append('biz', "jeditor");
            formData.append("jeditor","1");
            uploadAction(window._CONFIG['domianURL']+"/sys/common/upload", formData).then((res) => {
              if (res.success) {
                if(res.message == 'local'){
                  const img = 'data:image/jpeg;base64,' + blobInfo.base64()
                  success(img)
                }else{
                  let img = getFileAccessHttpUrl(res.message)
                  success(img)
                }
              }
            })
          },
          /**
           * 该事件在saveBtn插件的按钮点击时触发
           * @param data
           * @param editor
           */
          save_handler:(data,editor)=>{
            this.$emit('onsave', {data,editor})
            console.log(data);
          }
        },
        myValue: this.value,
        reloading: false,
      }
    },
    mounted() {
      // this.initATabsChangeAutoReload()
      this.reload();
    },
    methods: {

      reload() {
        this.reloading = true
        this.$nextTick(() => this.reloading = false)
      },

      onClick(e) {
        this.$emit('onClick', e, tinymce)
      },
      //可以添加一些自己的自定义事件，如清空内容
      clear() {
        this.myValue = ''
      },

      /**
       * 自动判断父级是否是 <a-tabs/> 组件，然后添加事件监听，自动触发reload()
       *
       * 由于 tabs 组件切换会导致 tinymce 无法输入，
       * 只有重新加载才能使用（无论是vue版的还是jQuery版tinymce都有这个通病）
       */
      initATabsChangeAutoReload() {
        debugger;
        // 获取父级
        /*let tabs = getVmParentByName(this, 'ATabs')
        let tabPane = getVmParentByName(this, 'ATabPane')*/
        let tabs = undefined;
        let tabPane = undefined;
        if (tabs && tabPane) {
          // 用户自定义的 key
          let currentKey = tabPane.$vnode.key
          // 添加事件监听
          tabs.$on('change', (key) => {
            // 切换到自己时执行reload
            if (currentKey === key) {
              this.reload()
            }
          })
          //update--begin--autor:liusq-----date:20210316------for：富文本编辑器tab父组件可能导致的赋值问题------
          this.reload()
          //update--end--autor:liusq-----date:20210316------for：富文本编辑器tab父组件可能导致的赋值问题------
        }else{
          //update--begin--autor:wangshuai-----date:20200724------for：富文本编辑器切换tab无法修改------
          let tabLayout = getVmParentByName(this, 'TabLayout')
          //update--begin--autor:liusq-----date:20210713------for：处理特殊情况excuteCallback不能使用------
          try {
            tabLayout.excuteCallback(() => {
              this.reload()
            })
          } catch (error) {
            if (tabLayout) {
              this.reload()
            }
          }
          //update--end--autor:liusq-----date:20210713------for：处理特殊情况excuteCallback不能使用------
          //update--begin--autor:wangshuai-----date:20200724------for：文本编辑器切换tab无法修改------
        }
      },

    },
    watch: {
      value(newValue) {
        this.myValue = (newValue == null ? '' : newValue)
      },
      myValue(newValue) {
        if(this.triggerChange){
          this.$emit('change', newValue)
        }else{
          this.$emit('input', newValue)
        }
      }
    }
  }

</script>
<style scoped>
.tinymce-editor{
  //width: 375px;
  width: 100%;
}
#switchMobilePc{display: none;}



.ant-table-body colgroup,.ant-table-thead th[key="create_by_id"],.ant-table-thead th[key="category_code"],.ant-table-thead th[key="category_id"],.ant-table-thead th[key="copyfrom"],.ant-table-thead th[key="href"],.ant-table-tbody tr td:nth-of-type(2),.ant-table-tbody tr td:nth-of-type(6),.ant-table-tbody tr td:nth-of-type(7),.ant-table-tbody tr td:nth-of-type(10),.ant-table-tbody tr td:nth-of-type(11){display:none;}
/*document.querySelector('input[value="create_by_id"]').click();
document.querySelector('input[value="category_code"]').click();
document.querySelector('input[value="category_id"]').click();
document.querySelector('input[value="copyfrom"]').click();
document.querySelector('input[value="href"]').click();*/


</style>


